package com.example.payment.service.impl;

import com.example.common.Interface.order.entity.dto.IsValidOrderIdReqDTO;
import com.example.common.Interface.order.service.OrderService;
import com.example.common.Interface.payment.entity.dto.ChargeReqDTO;
import com.example.common.Interface.payment.entity.dto.ChargeRespDTO;
import com.example.common.Interface.payment.service.PaymentService;
import com.example.common.response.BizException;
import com.example.common.response.HttpStatusEnum;
import com.example.payment.dao.mapper.TransactionMapper;
import com.example.payment.dao.po.Transaction;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

@DubboService
@Slf4j
@Service
public class PaymentServiceImpl implements PaymentService {

    @Resource
    private TransactionMapper TransactionMapper;

    @DubboReference(check = false)
    private OrderService orderService;

    private int random() {
        return (int) (Math.random() * 100);
    }

    @Override
    public ChargeRespDTO Charge(ChargeReqDTO chargeReq) {
        log.info("Charge rpc 服务被调用");

        var amount = chargeReq.getAmount();
        if (amount < 0) {
            log.warn("金额小于0");
            throw new BizException(100, "金额小于0");
        }

        var creditCard = chargeReq.getCreditCard();
        if (!creditCard.isValidCreditCard()) {
            log.warn("信用卡信息无效");
            throw new BizException(100, "信用卡信息无效");
        }

        var orderId = chargeReq.getOrderId();

        var isValid = orderService.isValidOrderId(IsValidOrderIdReqDTO.builder()
                .orderId(orderId).build()).isValid();

        if (!isValid) {
            log.warn("订单号验证失败");
            throw new BizException(HttpStatusEnum.UNAUTHORIZED);
        }

        var userId = chargeReq.getUserId();
        if (userId <= 0) {
            log.warn("用户id不合法");
            throw new BizException(100, "用户id不合法");
        }
        // 这里应该调用第三方支付接口，这里只是模拟 todo

//        if (random() % 2 == 0) {
//            log.warn("Charge rpc 模拟支付失败");
//            throw new BizException(100, "Charge rpc 模拟支付失败");
//        }
        log.info("Charge rpc 模拟支付成功");
        Transaction transaction = Transaction.builder()
                .amount(amount)
                .creditCard(creditCard.serialize())
                .userId(userId)
                .orderId(orderId).build();

        int num = TransactionMapper.insert(transaction);
        if (num != 1) {
            log.warn("Charge rpc 交易插入数据库失败");
            throw new BizException(100, "Charge rpc 交易插入数据库失败");
        }

        return ChargeRespDTO.builder()
                .transactionId(transaction.getId().toString()).build();
    }
}
